package com.byx.imclientutil.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * HeartBeatHandler
 *
 * @author Superb
 * @date 2021/4/4 17:18
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    private NettyWebSocketClientImpl imService;
    private HeartBeatTask heartBeatTask;

    public HeartBeatHandler(NettyWebSocketClientImpl imService) {
        this.imService = imService;
    }

    /**
     * Calls {@link ChannelHandlerContext#fireUserEventTriggered(Object)} to forward
     * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     * @param evt
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleState state = ((IdleStateEvent) evt).state();
            switch (state){
                case READER_IDLE:
                    // 规定时间内没收到服务端发送的心跳包，就进行重连
                    imService.reconnect(false);
                    break;
                case WRITER_IDLE:
                    // 规定时间内没向服务端发送心跳包，就发送一个心跳包
                    if (heartBeatTask == null) {
                        heartBeatTask = new HeartBeatTask(ctx,imService);
                    }
                    imService.getExecutors().execWorkTask(heartBeatTask);
                    break;
                default:break;
            }
        }
    }
}
